package com.config;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

/**
 * redis核心类
 * @author dell
 *
 */
@Component
public class RedisService {

	@Autowired
	@Qualifier("redisTemplate")
	RedisTemplate redisTemp;
	
	/**
	 * 从队列中取出一条信息
	 * @param queueName
	 */
	public String brpopQueueVal(String queueName)
	{
		return (String) redisTemp.opsForList().rightPop(queueName);
	}
	/**
	 * 像队列中插入一条信息
	 * @param queueName
	 * @param data
	 */
	public void pushQueueVal(String queueName,String data)
	{
		redisTemp.opsForList().leftPush(queueName, data);
	}
	
	/**
	 * 像redis插值
	 * @param key
	 * @param value
	 */
	public void setVal(String key,String value)
	{
		ValueOperations<String, Object> vo= redisTemp.opsForValue();
		vo.set(key, value);
	}
	/**
	 * 像redis插值
	 * @param key
	 * @param value
	 */
	public void setVal(String key,Object obj)
	{
		ValueOperations<String, Object> vo= redisTemp.opsForValue();
		vo.set(key, obj);
	}
	/**
	 * 获取值
	 * @param key
	 */
	public Object getVal(String key)
	{
		ValueOperations<String, Object> vo=redisTemp.opsForValue();
		return vo.get(key);
	}
	/**
	 * 获取值
	 * @param key
	 */
	public String getStrVal(String key)
	{
		String res=null;
		ValueOperations<String, Object> vo=redisTemp.opsForValue();
		Object obj=vo.get(key);
		if(obj!=null)res=obj.toString();
		return res;
	}
	/**
	 * 像redis插值，time时间后过期，时间为分
	 * @param key
	 * @param value
	 * @param time
	 */
	public void setVal(String key,String value,int time)
	{
		ValueOperations<String, Object> vo=redisTemp.opsForValue();
		vo.set(key, value);
		redisTemp.expire(key, time, TimeUnit.MINUTES);//设置过期时间
	}
	/**
	 * 像redis插值，time时间后过期，时间为分
	 * @param key
	 * @param value
	 * @param time
	 */
	public void setVal(String key,Object obj,int time)
	{
		ValueOperations<String, Object> vo=redisTemp.opsForValue();
		vo.set(key, obj);
		redisTemp.expire(key, time, TimeUnit.MINUTES);//设置过期时间
	}
	
}
